package org.alala.user.web.framework.servlet;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

/**
 * 全局Exception处理
 * 
 * @author huojinguang
 */
public class UserExceptionHandler implements HandlerExceptionResolver {

	private static Logger logger = LoggerFactory.getLogger(UserExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		
		logger.error("Exception " + ex.getMessage(), ex);
		
		Properties props = new Properties();
		props.put("error_code", -4);
		props.put("error_desc", "服务器出错");
		props.put("exception", ex);
		
		try {
			response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			IOUtils.write(JSON.toJSONString(props), response.getOutputStream());
		} catch (IOException e) {
			logger.error("fail to write data to response", e);
		}
		return null;
	}
}
